#include <systemInit.h>
#include <hwProtection.h>
#include <ledParamTables.h>
#include <colorMixingTask.h>

void HwardwareOverTempISR(void)
{
  
}

void HwardwareOverVoltISR(void)
{
  
}

void HwardwareUnderVoltISR(void)
{
  
}


void PWMs_Init(void)
{
    for (PwmChannel_t i = PWM_CHANNEL_0; i <= PWM_CHANNEL_23;i++){
        PWM_SetMaxChannelCurrent(i,   CURR_30MA);       //最大电流30MA
    }
    PWM_Init(PWM_PRESCALER_DIVIDE_1, PWM_VALUE_MAX, false);
    for (PwmChannel_t i = PWM_CHANNEL_0; i <= PWM_CHANNEL_23;i++){
        PWM_SetMatchValue(i, 0, 0);                     //PWM的比较直
    }
    for (PwmChannel_t i = PWM_CHANNEL_0; i <= PWM_CHANNEL_23;i++){
        PWM_Enable(i);
    }
}


void SYS_Init(void)
{
//    SYSCTRLA_SFRS->DEBUG_ACCESS_KEY.DEBUG_ACCESS_KEY = 0x05u;
  
//    // hardware over temperature protection
//    HW_PROT_SetOverTmperature(OVT_PROT_130C, OVT_ACTION_IRQ);
//    HW_PROT_RegisterOVTemperatureIRQ(HwardwareOverTempISR);
  
//    // hardware over volt protection
//    HW_PROT_SetOverVoltage(OV_VOLT_18400mV);
//    HW_PROT_RegisterOverVoltageIRQ(HwardwareOverVoltISR);
  
//    // hardware under volt protection
//    HW_PROT_SetUnderVoltage(UV_VOLT_6136mV);
//    HW_PROT_RegisterUnderVoltageIRQ(HwardwareUnderVoltISR);
  
    Clock_SystemMainClockInit(CLOCK_RC_16MHz, SYS_MAIN_CLOCK_DIV);              //16M主频 1分频
    SysTick_Init(SOFT_TIMER_INTERVAL *1000 * MAIN_CPU_CLOCK, SoftTimer_ExpireCallback); //定时器 10ms
    
    PWM_EnableBuck();           //使能PWM的Buck电路
    PWMs_Init();
    
    LedCoordinate_t param = {           //LED校准参数
        .red.x = (uint16_t)(0.6880*65535),
        .red.y = (uint16_t)(0.3085*65535),
        .red.intensity = 851,
        .green.x = (uint16_t)(0.1681*65535),
        .green.y = (uint16_t)(0.6938*65535),
        .green.intensity = 1600,
        .blue.x = (uint16_t)(0.1436*65535),
        .blue.y = (uint16_t)(0.0519*65535),
        .blue.intensity = 450,
    };
    
    Coordinate_t white = {              //白光校准参数
      .x = (uint16_t)(0.3333*65535),
      .y = (uint16_t)(0.3333*65535)
    };
    
    //LED 0~5的参数设定
    for (LedNumber_t i = LED0; i <= LED5; i++ ){
        CLM_SetLedPhyParams(ROOM_TEMPERATURE,  i, &param);              //室温25度
        CLM_DoWhitePointCalculating(ROOM_TEMPERATURE,i,white);
    }

    //初始化任务
    TM_PostTask(TASK_ID_SOFT_TIMER);
    TM_PostTask(TASK_ID_LINS);
#if LIN_MASTER_EN == 1
    TM_PostTask(TASK_ID_LINM);
#endif
    TM_PostTask(TASK_ID_ADC);
    TM_PostTask(TASK_ID_COLOR_MIXING);
    TM_PostTask(TASK_ID_APPL);
}